import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import '../../widgets/lineChartSample.dart';

class PolluteDetail extends StatefulWidget {
  List<double> spots;
  List<String> xTitle;
  String typeName;
  String typeValue;

  PolluteDetail({
    super.key,
    this.spots = const [20, 40, 90, 30, 80, 20],
    this.xTitle = const ['12', '22', '32', '42', '52', '62'],
    this.typeName = 'SO₂',
    this.typeValue = '20',
  });

  @override
  _PolluteDetailState createState() => _PolluteDetailState();
}

class _PolluteDetailState extends State<PolluteDetail>
    with TickerProviderStateMixin {
  late TabController _tabController;
  String dateNow =
      "${DateTime.now().year}.${DateTime.now().month.toString().padLeft(2, '0')}.${DateTime.now().day.toString().padLeft(2, '0')}"; // 默认今天年月日

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<List<dynamic>> _fetchSteelOutHourData(String date) async {
    final NetworkService _networkService = NetworkService();
    try {
      final response = await _networkService.get(
          '/plcTimer/steelouthour/dayInfoList',
          queryParameters: {'date': date});
      if (response.statusCode == 200) {
        final rows = response.data['rows']; // 假设返回的数据是一个列表
        setState(() {
          // 根据 typeName 筛选不同类型的数据
          String dataField;
          switch (widget.typeName) {
            case 'SO₂':
              dataField = 'gasAccuTotal';
              break;
            case '颗粒物含量':
              dataField = 'o2AccuTotal';
              break;
            case 'Nox含量':
              dataField = 'n2AccuTotal';
              break;
            default:
              dataField = 'gasAccuTotal'; // 默认值
          }
          widget.spots = rows.map<double>((row) {
            final value = double.tryParse(row[dataField].toString());
            if (value != null) {
              return value;
            } else {
              print('无法解析的值: ${row[dataField]}');
              return 0.0; // 或者选择其他默认值
            }
          }).toList();
          widget.xTitle = rows.map<String>((row) {
            final tjTime = row['tjTime'];
            if (tjTime != null) {
              return tjTime.toString();
            } else {
              print('无法解析的时间: ${row['tjTime']}');
              return ''; // 或者选择其他默认值
            }
          }).toList();
        });
        return rows;
      } else {
        print('加载钢铁出厂时间数据失败: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      print('Error in _fetchSteelOutHourData: $e');
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    // 设置为横屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
    ]);

    return WillPopScope(
      onWillPop: () async {
        // 页面返回时，调回竖屏
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
        return true;
      },
      child: Scaffold(
        backgroundColor: AppColors.backgroundColor,
        appBar: AppBar(
          title: SizedBox(
            child: Row(
              children: [
                Text(
                  '${widget.typeName}',
                  style: TextStyle(color: AppColors.textPrimary),
                ),
                SizedBox(
                  width: 20,
                ),
                Text(dateNow,
                    style: TextStyle(
                        color: const Color(0xFFFCAA3F), fontSize: 16)),
                Expanded(
                  child: SizedBox(),
                ),
                Image.asset(
                  'assets/images/centre/icon_date.png',
                  fit: BoxFit.cover,
                ),
                SizedBox(width: 5),
                TDButton(
                  text: '请选择日期',
                  textStyle:
                      TextStyle(fontSize: 14, color: AppColors.textSecondary),
                  size: TDButtonSize.medium,
                  type: TDButtonType.outline,
                  shape: TDButtonShape.rectangle,
                  theme: TDButtonTheme.defaultTheme,
                  style: TDButtonStyle(
                    backgroundColor: AppColors.cardColor,
                  ),
                  onTap: () {
                    TDPicker.showDatePicker(
                      context,
                      title: '选择时间',
                      pickerHeight: 120,
                      onConfirm: (selected) {
                        setState(() {
                          dateNow =
                              '${selected['year'].toString().padLeft(4, '0')}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}';
                          _fetchSteelOutHourData(dateNow);
                        });
                        Navigator.of(context).pop();
                      },
                      dateStart: [2000, 01, 01],
                      dateEnd: [2030, 12, 31],
                      initialDate: [
                        DateTime.now().year,
                        DateTime.now().month,
                        DateTime.now().day
                      ],
                    );
                  },
                )
              ],
            ),
          ),
          backgroundColor: Colors.transparent,
          flexibleSpace: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home/home_topbg.png'),
                fit: BoxFit.cover,
              ),
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Column(children: [
            Padding(
              padding: EdgeInsets.all(16),
              child: Container(
                  width: double.infinity,
                  // height: 100,
                  padding: EdgeInsets.all(16.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Row(
                    children: [
                      Text('${widget.typeName}：${widget.typeValue}（m³/t）',
                          style: TextStyle(
                              fontSize: 16, color: AppColors.textPrimary)),
                      SizedBox(
                        width: 20,
                      ),
                      Text('排放达标率：90%',
                          style: TextStyle(
                              fontSize: 16, color: AppColors.textPrimary)),
                      SizedBox(
                        width: 20,
                      ),
                      Text('最大值：23（m³/t）',
                          style: TextStyle(
                              fontSize: 16, color: AppColors.textPrimary)),
                      SizedBox(
                        width: 20,
                      ),
                      Text('最小值：17（m³/t）',
                          style: TextStyle(
                              fontSize: 16, color: AppColors.textPrimary)),
                    ],
                  )),
            ),
            Padding(
              padding: EdgeInsets.only(left: 16, right: 16, bottom: 16),
              child: Container(
                  width: double.infinity,
                  // height: 100,
                  padding: EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    color: AppColors.cardColor,
                    borderRadius: BorderRadius.circular(8.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.2),
                        blurRadius: 6.0,
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      Row(children: [
                        TDTabBar(
                          // width: 300,
                          tabs: const [
                            TDTab(
                              text: '日',
                            ),
                            TDTab(
                              text: '周',
                            ),
                            TDTab(
                              text: '年',
                            ),
                          ],
                          controller: _tabController,
                          labelColor: Color(0xFF2AB6F7),
                          unselectedLabelColor: AppColors.textSecondary,
                          indicatorColor: Color(0xFF2AB6F7),
                          dividerColor: Colors.transparent,
                          backgroundColor: Colors.transparent,
                          showIndicator: true,
                          width: 300,
                          onTap: (index) {
                            setState(() {
                              // 根据选中的标签更新数据
                              switch (index) {
                                case 0:
                                  String d = DateTime.parse(dateNow)
                                      .toString()
                                      .substring(0, 10);
                                  // 更新为日产量数据
                                  _fetchSteelOutHourData(d);
                                  break;
                                case 1:
                                  String d = DateTime.parse(dateNow)
                                      .toString()
                                      .substring(0, 7);
                                  // 更新为月产量数据
                                  _fetchSteelOutHourData(d);
                                  break;
                                case 2:
                                  String d = DateTime.parse(dateNow)
                                      .toString()
                                      .substring(0, 4);
                                  // 更新为年产量数据
                                  _fetchSteelOutHourData(d);
                                  break;
                              }
                            });
                          },
                        ),
                        Text(
                          '(L)',
                          style: TextStyle(color: AppColors.textPrimary),
                        )
                      ]),
                      SizedBox(
                        height: 10,
                      ),
                      LineChartSample2(
                        spots: widget.spots,
                        xTitle: widget.xTitle,
                        aspectRatio: 4.0,
                      ),
                    ],
                  )),
            ),
          ]),
        ),
      ),
    );
  }
}
